import React, { useState, useEffect } from 'react';
import { Table, message, Card, Tag, Row, Col, Statistic, Space, Typography, Badge } from 'antd';
import { getBorrowList } from '../../../services/api';
import moment from 'moment';
import 'moment/locale/zh-cn';
import BorrowStatusFilter from '../../Filter/BorrowStatusFilter';
import { ClockCircleOutlined, CheckCircleOutlined, ExclamationCircleOutlined, AppstoreOutlined } from '@ant-design/icons';

const { Title } = Typography;

// 自定义背景样式组件
const BackgroundDecorator = () => (
  <div style={{
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    zIndex: 0,
    background: 'linear-gradient(120deg, #e0c3fc 0%, #8ec5fc 100%)',
    opacity: 0.15,
  }}>
    {/* 左上角装饰 */}
    <div style={{
      position: 'absolute',
      top: '5%',
      left: '2%',
      width: '300px',
      height: '300px',
      background: 'linear-gradient(45deg, #4facfe 0%, #00f2fe 100%)',
      borderRadius: '30% 70% 70% 30% / 30% 30% 70% 70%',
      opacity: 0.1,
      transform: 'rotate(-15deg)',
    }} />
    {/* 右上角装饰 */}
    <div style={{
      position: 'absolute',
      top: '10%',
      right: '5%',
      width: '200px',
      height: '200px',
      background: 'linear-gradient(45deg, #fa709a 0%, #fee140 100%)',
      borderRadius: '62% 38% 46% 54% / 60% 51% 49% 40%',
      opacity: 0.1,
    }} />
    {/* 左下角装饰 */}
    <div style={{
      position: 'absolute',
      bottom: '15%',
      left: '10%',
      width: '250px',
      height: '250px',
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
      borderRadius: '41% 59% 37% 63% / 57% 44% 56% 43%',
      opacity: 0.1,
    }} />
    {/* 右下角装饰 */}
    <div style={{
      position: 'absolute',
      bottom: '5%',
      right: '2%',
      width: '280px',
      height: '280px',
      background: 'linear-gradient(45deg, #13547a 0%, #80d0c7 100%)',
      borderRadius: '53% 47% 52% 48% / 44% 48% 52% 56%',
      opacity: 0.1,
    }} />
  </div>
);

const BorrowListUsr = () => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [filteredData, setFilteredData] = useState([]);
  const [currentUser, setCurrentUser] = useState(null);
  const [statusFilter, setStatusFilter] = useState(null);
  const [statistics, setStatistics] = useState({
    total: 0,
    borrowing: 0,
    returned: 0,
    pending: 0
  });

  // 设置 moment 为中文
  moment.locale('zh-cn');

  useEffect(() => {
    // 从 sessionStorage 获取当前用户信息
    const userInfo = JSON.parse(sessionStorage.getItem('user') || '{}');
    setCurrentUser(userInfo);
  }, []);

  const formatDate = (dateString) => {
    if (!dateString) return '';
    
    // 如果是中文格式的日期，先用 moment 解析
    if (typeof dateString === 'string' && dateString.includes('月')) {
      const m = moment(dateString, 'MMMM DD, YYYY', 'zh-cn');
      if (m.isValid()) {
        return m.format('YYYY-MM-DD');
      }
    }
    
    // 如果是长整数形式的时间戳字符串，需要转换为数字
    if (typeof dateString === 'string' && !isNaN(dateString)) {
      return moment(parseInt(dateString)).format('YYYY-MM-DD');
    }
    
    // 如果已经是数字类型的时间戳
    if (typeof dateString === 'number') {
      return moment(dateString).format('YYYY-MM-DD');
    }
    
    // 其他情况尝试直接解析
    const m = moment(dateString);
    if (m.isValid()) {
      return m.format('YYYY-MM-DD');
    }
    
    return '';
  };

  const fetchBorrowList = async () => {
    setLoading(true);
    try {
      const response = await getBorrowList();
      if (response.code === 200 && currentUser?.uId) {
        // 只显示当前用户的借用记录
        const filteredData = response.data.filter(item => item.uId === currentUser.uId);
        // 格式化日期
        const formattedData = filteredData.map(item => ({
          ...item,
          borrowTime: formatDate(item.borrowTime),
          expectedReturnTime: formatDate(item.expectedReturnTime),
          actualReturnTime: formatDate(item.actualReturnTime)
        }));
        setData(formattedData);
        
        // 计算统计数据
        const stats = {
          total: formattedData.length,
          borrowing: formattedData.filter(item => item.borrowStatus === '借用中').length,
          returned: formattedData.filter(item => item.borrowStatus === '已归还').length,
          pending: formattedData.filter(item => item.borrowStatus === '待审批').length
        };
        setStatistics(stats);
      } else {
        message.error(response.message || '获取借用列表失败');
      }
    } catch (error) {
      console.error('获取借用列表失败:', error);
      message.error('获取借用列表失败');
    }
    setLoading(false);
  };

  useEffect(() => {
    if (currentUser) {
      fetchBorrowList();
    }
  }, [currentUser]);

  // 添加筛选效果
  useEffect(() => {
    if (statusFilter) {
      setFilteredData(data.filter(item => item.borrowStatus === statusFilter));
    } else {
      setFilteredData(data);
    }
  }, [statusFilter, data]);

  // 获取状态标签的样式
  const getStatusTag = (status) => {
    const statusConfig = {
      '借用中': { color: 'processing', icon: <ClockCircleOutlined />, text: '借用中' },
      '已归还': { color: 'success', icon: <CheckCircleOutlined />, text: '已归还' },
      '待审批': { color: 'warning', icon: <ExclamationCircleOutlined />, text: '待审批' },
      '已拒绝': { color: 'error', icon: <ExclamationCircleOutlined />, text: '已拒绝' }
    };
    const config = statusConfig[status] || { color: 'default', text: status };
    return (
      <Badge status={config.color} text={config.text} icon={config.icon} />
    );
  };

  const columns = [
    {
      title: '资产名称',
      dataIndex: 'assetName',
      key: 'assetName',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '借用数量',
      dataIndex: 'borrowNum',
      key: 'borrowNum',
      align: 'center',
    },
    {
      title: '借用时间',
      dataIndex: 'borrowTime',
      key: 'borrowTime',
      align: 'center',
    },
    {
      title: '预计归还时间',
      dataIndex: 'expectedReturnTime',
      key: 'expectedReturnTime',
      align: 'center',
    },
    {
      title: '实际归还时间',
      dataIndex: 'actualReturnTime',
      key: 'actualReturnTime',
      align: 'center',
    },
    {
      title: '借用状态',
      dataIndex: 'borrowStatus',
      key: 'borrowStatus',
      align: 'center',
      render: (status) => getStatusTag(status),
    },
    {
      title: '备注',
      dataIndex: 'borrowReason',
      key: 'borrowReason',
      ellipsis: true,
    }
  ];

  return (
    <div style={{ position: 'relative', minHeight: '100vh', padding: '20px' }}>
      {/* 背景图片层 */}
      <div style={{
        position: 'fixed',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundImage: 'url(/assets/flowers.jpg)',
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        backgroundRepeat: 'no-repeat',
        opacity: 0.8,
        zIndex: 0,
        pointerEvents: 'none'
      }} />

      {/* 内容层 */}
      <div style={{ 
        position: 'relative', 
        zIndex: 1,
        background: 'rgba(255, 255, 255, 0.9)',
        padding: '24px',
        borderRadius: '12px',
        boxShadow: '0 2px 12px rgba(0,0,0,0.1)'
      }}>
        <Space direction="vertical" size="large" style={{ width: '100%' }}>
          {/* 统计卡片和表格内容 */}
          <Row gutter={16}>
            <Col span={6}>
              <Card 
                size="small" 
                bodyStyle={{ padding: '12px' }}
                style={{ 
                  background: 'rgba(255, 255, 255, 0.85)',
                  borderRadius: '8px',
                  boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
                  transition: 'all 0.3s'
                }}
                hoverable
              >
                <Statistic
                  title={<span style={{ fontSize: '14px' }}>总借用次数</span>}
                  value={statistics.total}
                  valueStyle={{ color: '#1890ff', fontSize: '20px' }}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card 
                size="small" 
                bodyStyle={{ padding: '12px' }}
                style={{ 
                  background: 'rgba(255, 255, 255, 0.85)',
                  borderRadius: '8px',
                  boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
                  transition: 'all 0.3s'
                }}
                hoverable
              >
                <Statistic
                  title={<span style={{ fontSize: '14px' }}>当前借用</span>}
                  value={statistics.borrowing}
                  valueStyle={{ color: '#52c41a', fontSize: '20px' }}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card 
                size="small" 
                bodyStyle={{ padding: '12px' }}
                style={{ 
                  background: 'rgba(255, 255, 255, 0.85)',
                  borderRadius: '8px',
                  boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
                  transition: 'all 0.3s'
                }}
                hoverable
              >
                <Statistic
                  title={<span style={{ fontSize: '14px' }}>已归还</span>}
                  value={statistics.returned}
                  valueStyle={{ color: '#faad14', fontSize: '20px' }}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card 
                size="small" 
                bodyStyle={{ padding: '12px' }}
                style={{ 
                  background: 'rgba(255, 255, 255, 0.85)',
                  borderRadius: '8px',
                  boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
                  transition: 'all 0.3s'
                }}
                hoverable
              >
                <Statistic
                  title={<span style={{ fontSize: '14px' }}>待审批</span>}
                  value={statistics.pending}
                  valueStyle={{ color: '#ff4d4f', fontSize: '20px' }}
                />
              </Card>
            </Col>
          </Row>
          <Table
            columns={columns}
            dataSource={filteredData}
            loading={loading}
            pagination={{
              total: filteredData.length,
              pageSize: 10,
              showTotal: (total) => `共 ${total} 条记录`,
              showSizeChanger: true,
              showQuickJumper: true
            }}
            style={{ 
              background: 'white',
              borderRadius: '8px',
              overflow: 'hidden'
            }}
          />
        </Space>
      </div>
    </div>
  );
};

export default BorrowListUsr; 